from machine import ADC, Pin
from mpython import *

import time
import math
import ntptime
import urequests

NAME = "高一"  # 采集位置

adc = ADC(Pin(Pin.P0))  # 创建 ADC 对象
adc.atten(adc.ATTN_11DB)  # 设置 3.3v 范围
adc.width(3)  # 设置数据宽度

def get_dB():
    """获取分贝值"""
    vaule = adc.read()
    vaule = abs(vaule - 1876.467105)
    if value == 0:
        return 0
    return -38.83 + 41.25 * math.log(value, math.e) 

def get_time():
    """获取当前时间，为了便于数据整理，强制性将秒设为零"""
    t = time.localtime()
    return "%02d:%02d:00" % (t[3], t[4])

def get_mean(l):
    """求类别平均值"""
    x = sum(l) - min(l) - max(l)  # 求和，去最大最小值
    return x / len(l)

def print_oled(s):
    """便于控制台输出与oled显示的函数"""
    print(s)
    oled.fill(0)
    oled.DispChar(s, 0, 0, 1)
    oled.show()

print_oled("正在连接WIFI......")
mywifi = wifi()
mywifi.connectWiFi("WIFI名称", "WIFI密码")

print_oled("正在校准时间......")
print_oled("同步前本地时间：%s" % str(time.localtime()))
ntptime.settime()
print_oled("同步后本地时间：%s" % str(time.localtime()))

print_oled(get_time() + " 开始记录分贝值......")
f = open("result.csv", "w")  # 新建一个文件进行写入
f.write("时间,分贝值\n")  # 表头
history_dB = []

while True:
    time.sleep(1)
    
    dB = get_dB()
    
    print_oled("当前分贝值：" + str(dB))
    
    history_dB.append(dB)
    
    # 按照时间进行判断，可能会差1到5秒
    t = time.localtime()
    if 0 <= t[5] <= 5 and len(history_dB) >= 5:
        time_ = get_time()
        dB_m = get_mean(history_dB)
        print_oled("准备记录 " + time_ + "," + str(dB_m))
        f.write(time_ + "," + str(dB_m) + "\n")
        f.flush()  # 立刻写出
        r = urequests.get('http://ip:port?name=' + str(NAME) + "&time=" + time_ + "&data=" + str(dB_m))  # 请求 API 接口
        history_dB.clear()


